package com.sprite.framework.start.container;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
import com.sprite.framework.context.ContextEnvironment;
import com.sprite.framework.start.Container;
import org.slf4j.LoggerFactory;

import java.io.File;

public class LogbackContainer implements Container {

	public static final String LOGBACK_FILE = "logback.file";

	public static final String LOGBACK_LEVEL = "logback.level";

	public static final String LOGBACK_MAX_HISTORY = "logback.maxhistory";

	public static final String DEFAULT_LOGBACK_LEVEL = "ERROR";

	public void start() {
		String file = ContextEnvironment.getProperty(LOGBACK_FILE);
		if (file != null && file.length() > 0) {
			initLogback(file);
		}else {
			System.out.println("not found [logback.file], skiped LogbackContainer");
		}
	}

	public void stop() {
	}
	
	public static String loadPath(String base){
		if(!base.endsWith("\\")&&!base.endsWith("/")){
			return base + File.separator;
		}
		return base;
	}


	public static void initLogback(String base){
		LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
		try {
			JoranConfigurator configurator = new JoranConfigurator();
			configurator.setContext(lc);
			File conf = new File(loadPath(base));
			if (!conf.exists()) {
				System.out.println("not found "+conf.getPath()+", skiped LogbackContainer");
			} else {
				lc.reset();
				configurator.doConfigure(conf);
				LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).info("[logback initialized success...]");
			}
		} catch (JoranException je) {
			je.printStackTrace();
			StatusPrinter.print(lc.getStatusManager());
		}
	}

	@Override
	public void init(String[] args) {
		
	}
}